-- SERVER SIDE

CustomSpawnPoints = {}

-- Creates the Database
GetClMapN = string.Replace(game.GetMap(),"_","") 	//replace any underscores or
GetClMapN = string.Replace(GetClMapN,".","")	//periods, they don't work for file names
GetClMapNN = "apple_tmd99_"..GetClMapN
if sql.TableExists(GetClMapNN) then
--MsgN("[TDM-CustomSpawns] Database '"..GetClMapNN.."' Already Exists!")
MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-CustomSpawnsDB",Color(255,255,255),"] Database '"..GetClMapNN.."' Already Exists!\n")
	else
		if (!sql.TableExists(GetClMapNN)) then
			local Query = "CREATE TABLE "..GetClMapNN.." ( TID int, ID int(255), XPos varchar(255), YPos varchar(255), ZPos varchar(255), Pitch varchar(255), Yaw varchar(255), Roll varchar(255))"
			local Result = sql.Query(Query)
			if (sql.TableExists(GetClMapNN)) then
				--MsgN("[TDM-CustomSpawns] Successfully Created Database '"..GetClMapNN.."'!")
				MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-CustomSpawnsDB",Color(255,255,255),"] Successfully Created Database '"..GetClMapNN.."'!\n")
			else
				--MsgN("[TDM-CustomSpawns] Database '"..GetClMapNN.."' Was Not Created!")
				MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-CustomSpawnsDB",Color(255,255,255),"]  Database '"..GetClMapNN.."' Was Not Created!\n")
				MsgN( sql.LastError( Result ) )
			end	
		end
end


function CreateSTList()
local GetTeamInfoAll2 = sql.Query( "SELECT * FROM "..GetClMapNN.."" )
	if !GetTeamInfoAll2 then 
		--MsgN("[TDM-CustomSpawns] Does Not Exist!")
		MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-CustomSpawnsFix",Color(255,255,255),"]  Does Not Exist!\n")
		local oldpoints = ents.FindByClass("team_spawn")
		for _,v in pairs(oldpoints) do v:Remove() end
		umsg.Start("apple_tdm_customspawn312")
		umsg.End()
	return end
	
CustomSpawnPoints = {}
	
	local oldpoints = ents.FindByClass("team_spawn")
	for _,v in pairs(oldpoints) do v:Remove() end
	
	for k, v in pairs( GetTeamInfoAll2 ) do
	CustomSpawnPoints[k] = {
		TID = tonumber(v['TID']),
		ID = tonumber(v['ID']),
		XPos = tonumber(v['XPos']),
		YPos = tonumber(v['YPos']),
		ZPos = tonumber(v['ZPos'])
	}
	local ent = ents.Create("team_spawn")
		ent:SetPos(Vector(tonumber(v['XPos']),tonumber(v['YPos']),tonumber(v['ZPos'])))
		ent:SetAngles(Angle(tonumber(v['Pitch']),tonumber(v['Yaw']),tonumber(v['Roll'])))
		ent:SetModel("models/props_trainstation/TrackSign03.mdl")
		ent:SetColor(team.GetColor(tonumber(v['TID'])))
		ent:Spawn()
	end
	
	net.Start( "apple_tdm_customspawn31" )
		net.WriteTable(CustomSpawnPoints)
	net.Broadcast()
end


function UpdateSPList()
	net.Start( "apple_tdm_customspawn31" )
		net.WriteTable(CustomSpawnPoints)
	net.Broadcast()
end


function TDMGotoPos(len, ply)
if !ply:IsSuperAdmin() then return end
local XPos = net.ReadString( )
local YPos = net.ReadString( )
local ZPos = net.ReadString( )
ply:SetPos(Vector(XPos,YPos,ZPos))
umsg.Start("apple_tdm_wentpos", ply)
	umsg.Short(XPos)
	umsg.Short(YPos)
	umsg.Short(ZPos)
umsg.End()
end
net.Receive("TDMGotoPos", TDMGotoPos)


function TDMRemovePos(len, ply)
if !ply:IsSuperAdmin() then return end
local TeamID = net.ReadString( )
local SpawnID = net.ReadString( )
	local GetSpawnInfo222 = sql.Query( "SELECT * FROM "..GetClMapNN.." WHERE ID = "..SpawnID.." AND TID = "..TeamID.."" )
	local GetSpawnInfo = sql.Query( "DELETE FROM "..GetClMapNN.." WHERE ID = "..SpawnID.." AND TID = "..TeamID.."" )
		if !GetSpawnInfo then 
			--MsgN("[TDM-CustomSpawns] Spawn Point Was Deleted")
			MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-CustomSpawnsDelete",Color(255,255,255),"] Spawn Point Was Deleted\n")
				for k, v in pairs( GetSpawnInfo222 ) do
					umsg.Start("apple_tdm_deletepos", ply)
						umsg.Short(TeamID)
						umsg.Short(v.XPos)
						umsg.Short(v.YPos)
						umsg.Short(v.ZPos)
					umsg.End()
				end
		end
	local GetSpawnInfo3 = sql.Query( "SELECT * FROM "..GetClMapNN.." WHERE TID = "..TeamID.." AND ID >"..SpawnID )
		if GetSpawnInfo3 then 
			for k, v in pairs( GetSpawnInfo3 ) do
				sql.Query( "UPDATE "..GetClMapNN.." SET ID = "..(tonumber(v.ID)-1).." WHERE TID = "..TeamID.." AND ID = "..v.ID.."" )
			end
			CreateSTList()
		else
			CreateSTList()
		end
end
net.Receive("TDMRemovePos", TDMRemovePos)


function TDMAddPos(len, ply)
if !ply:IsSuperAdmin() then return end
local TeamID = net.ReadString( )
	LastSpawnIDCreated = nil
	LastSpawnIDCreated = sql.QueryValue( "SELECT COUNT(ID) FROM "..GetClMapNN.." WHERE TID = "..TeamID.."" )
	
	if LastSpawnIDCreated == nil then
		LastSpawnIDCreated = 0
	end
	
	LastSpawnIDCreated = (LastSpawnIDCreated + 1)
		
	local vAngle = ply:GetAimVector()
	local UpAngle = tostring(vAngle:Angle())
	local data = string.Explode(" ", UpAngle)

--	local UpAngle = tostring(ply:EyePos())
--	local data = string.Explode(" ", UpAngle)

	local AddTSDLF = sql.Query( "INSERT INTO "..GetClMapNN.." (`TID`, `ID`, `XPos`, `YPos`, `ZPos`, `Pitch`, `Yaw`, `Roll`) VALUES ('"..tonumber(TeamID).."', '"..LastSpawnIDCreated.."', '"..math.Round(tonumber(ply:GetPos().x)).."', '"..math.Round(tonumber(ply:GetPos().y)).."', '"..math.Round(tonumber(ply:GetPos().z)).."', '"..math.Round(tonumber(data[1])).."', '"..math.Round(tonumber(data[2])).."', '"..math.Round(tonumber(data[3])).."' ) ")
	if !AddTSDLF then 
		--MsgN("[TDM-CustomSpawns] Spawn Point Was Created")
		MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-CustomSpawnsAdd",Color(255,255,255),"] Spawn Point Was Created\n")
		umsg.Start("apple_tdm_createdpos", ply)
			umsg.Short(TeamID)
			umsg.Short(tonumber(ply:GetPos().x))
			umsg.Short(tonumber(ply:GetPos().y))
			umsg.Short(tonumber(ply:GetPos().z))
		umsg.End()
		CreateSTList()
	return end
end
net.Receive("TDMAddPos", TDMAddPos)